<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Admins;
use Carbon\Carbon;
use Illuminate\Http\Request;

class ManagerController extends Controller {

    public function index(Request $request){
        $params = [
            'username'  => (string)$request->get('username',''),
        ];
        $lists = Admins::where(function ($query) use ($params) {
                if($params['username']) {
                    $query ->where('username','like','%' . $params['username'] . '%');
                }
            })->orderBy('created_at', 'desc')
            ->paginate(10);
        $this->stateToText($lists,[
            'status' => Admins::STATUS_TEXT,
        ]);
        return $this->writeJson(0,$lists);
    }

    public function update(Request $request)
    {
        $data = $request->all();
        if($data['id']){
            $info = Admins::findOrFail($data['id']);
            if($data['password']){
                $data['password'] = bcrypt($data['password']);
            }else{
                unset($data['password']);
            }
            $info->update($data);
            return $this->writeJson(0,null,'修改管理员信息成功');
        }else{
            $user = Admins::where('username',$data['username'])->first();
            if($user){
                return $this->writeJson(1,null,'该账号已经存在');
            }
            $data['password'] = $data['password'] ? bcrypt($data['password']) : bcrypt('123456');
            $data['login_at'] = Carbon::now();
            $data['login_ip'] = $request->getClientIp();
            Admins::create($data);
            return $this->writeJson(0,null,'新增管理员信息成功');
        }
    }

    public function lock(Request $request){
        $id = (int)$request->get('id',0);
        if(empty($id)){
            return $this->writeJson(1,null,'参数错误');
        }
        $info = Admins::findOrFail($id);
        if(empty($info)){
            return $this->writeJson(1,null,'数据不存在');
        }
        $info->update(['status'=>Admins::STATUS_2]);
        return $this->writeJson(0);
    }

    public function unlock(Request $request){
        $id = (int)$request->get('id',0);
        if(empty($id)){
            return $this->writeJson(1,null,'参数错误');
        }
        $info = Admins::findOrFail($id);
        if(empty($info)){
            return $this->writeJson(1,null,'数据不存在');
        }
        $info->update(['status'=>Admins::STATUS_1]);
        return $this->writeJson(0);
    }

    public function destroy(Request $request){
        $id = (int)$request->get('id',0);
        if(empty($id)){
            return $this->writeJson(1,null,'参数错误');
        }
        Admins::destroy($id);
        return $this->writeJson(0);
    }

}
